package com.nimble.smile.activity;

import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.nimble.smile.service.CheckLogoutOperator;
import com.nimble.smile.service.Service;
import com.nimble.smile.service.ServiceManager;
import com.nimble.smile.utils.RxAndroidUtil;
import com.nimble.smile.utils.UIHelper;
import com.trello.rxlifecycle.components.support.RxFragmentActivity;

import rx.Observable;
import rx.functions.Action0;
import rx.functions.Action1;

/**
 * Created by simon on 17-5-3.
 */

public class BaseActivity extends RxFragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

    }

    protected Service getService() {
        return ServiceManager.getInstance().getService();
    }

    protected <T> void subscribe(Observable<T> observable, Action1<T> onNext) {
        RxAndroidUtil.subscribe(this, toCheckoutLogoutObservable(observable), onNext, this::handleError);
    }

    protected <T> void subscribe(Observable<T> observable, Action1<T> onNext, Action0 onComplete) {
        RxAndroidUtil.subscribe(this, toCheckoutLogoutObservable(observable), onNext, this::handleError, onComplete);
    }

    protected <T> void subscribe(Observable<T> observable, Action1<T> onNext, Action1<Throwable> onError) {
        RxAndroidUtil.subscribe(this, toCheckoutLogoutObservable(observable), onNext, onError);
    }

    <T> Observable<T> toCheckoutLogoutObservable(Observable<T> observable) {
        return observable.lift(new CheckLogoutOperator<>());
    }

    protected void showToast(String content) {
        Toast.makeText(this, content, Toast.LENGTH_SHORT).show();
    }

    protected void showToast(int resId) {
        Toast.makeText(this, resId, Toast.LENGTH_SHORT).show();
    }

    public void handleError(Throwable t) {
        hideProgressDialog();
        showToast(t.getMessage());
        Log.e(this.getClass().getName(), "request failed", t);
    }

    public void showProgressDialog(String str) {
        hideProgressDialog();
        UIHelper.getInstance().showProgressDialog(this, str);
    }

    public void hideProgressDialog() {
        UIHelper.getInstance().hideProgressDialog();
    }
}
